package com.ztjava.data.controller;

import java.util.List;

import com.jfinal.aop.Duang;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.BackMethod;
import com.ztjava.core.base.BaseController;
import com.ztjava.data.model.DataRegion;
import com.ztjava.data.service.DataService;

public class DataController extends BaseController{
	public void getSubRegion(){
		Integer parent_id = getParaToInt("parent_id",0);
		List<DataRegion> list = CacheKit.get(Constant.CacheAutoClear, "DATA_REGION_PARENT_ID_"+parent_id);
		if(list==null){
			list = DataRegion.dao.find("select id,parent_id,CONCAT(province,city,district) as name,code from "+DataRegion.tablename+" where parent_id=?",parent_id);
			CacheKit.put(Constant.CacheAutoClear, "DATA_REGION_PARENT_ID_"+parent_id, list);
		}
		setAttr("list", list);
		setAttr("result","success");
		renderJson(new String[]{"result","list"});
	}
	
	@BackMethod("DataRegion")
	public void regionList(){
		List<DataRegion> regionList =  DataRegion.dao.find("select id,parent_id as pId,CONCAT(province,city,district) as name,code from "+DataRegion.tablename);
		setAttr("regionJSON", JsonKit.toJson(regionList));
		renderBackTpl("/data/regionList.html");
	}

	@BackMethod("DataRegion")
	public void addEditRegion(){
		Integer id = getParaToInt("id",0);
		DataRegion dataRegion = new DataRegion();
		if(id>0){
			dataRegion = DataRegion.dao.findById(id);
		}else {
			Integer parent_id = getParaToInt("parent_id",0);
			dataRegion.set("parent_id", parent_id);
		}
		if(dataRegion.getInt("parent_id")>0){
			DataRegion parentRegion = DataRegion.dao.findById(dataRegion.getInt("parent_id"));
			setAttr("parentRegion", parentRegion);
		}
		setAttr("dataRegion", dataRegion);
		renderBackTpl("/data/addEditRegion.html");
	}
	@BackMethod("DataRegion")
	public void saveRegion(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		DataRegion dataRegion = getModel(DataRegion.class);
		DataService dataService = Duang.duang(DataService.class);
		if(dataService.isRepeat(dataRegion, DataRegion.tablename, "code")){
			renderError("区划编码重复！");
			return;
		}
		if(dataRegion.get("province")==null) dataRegion.set("province", "");
		if(dataRegion.get("city")==null) dataRegion.set("city", "");
		if(dataRegion.get("district")==null) dataRegion.set("district", "");
		saveModel(dataRegion, user_id);
		setAttr("result", "success");
		setAttr("message", "保存成功！");
		setAttr("object", dataRegion);
		renderJson(new String[]{"result","message","object"});
	}

	@BackMethod("DataRegion")
	public void deleteRegion(){
		Integer id = getParaToInt("id");
		DataRegion child = DataRegion.dao.findFirst("select id from "+DataRegion.tablename+" where parent_id=?",id);
		if(child!=null){
			renderError("存在子节点无法删除！");
			return;
		}
		Db.deleteById(DataRegion.tablename, id);
		renderSuccess("删除成功！");
	}
}
